import { Command } from "commander";
import { Stress } from "./Stress";
import { BridgeConfig } from "../core/BridgeConfig";
import * as fs from "fs";

export type StressArgs = {
    config: BridgeConfig;
    parallelCreates: number;
    createIterations: number;
    parallelClaims: number;
    claimIterations: number;
};

const parse = (args: any): StressArgs | undefined => {
    const validNumber = (n: any): boolean => !isNaN(Number(n)) && Number(n) >= 0;
    if (
        args.config &&
        args.parallelCreates &&
        validNumber(args.parallelCreates) &&
        args.createIterations &&
        validNumber(args.createIterations) &&
        args.parallelClaims &&
        validNumber(args.parallelClaims) &&
        args.claimIterations &&
        validNumber(args.claimIterations)
    ) {
        return {
            config: new BridgeConfig(JSON.parse(fs.readFileSync(args.config).toString())),
            parallelCreates: Math.floor(Number(args.parallelCreates)),
            createIterations: Math.floor(Number(args.createIterations)),
            parallelClaims: Math.floor(Number(args.parallelClaims)),
            claimIterations: Math.floor(Number(args.claimIterations)),
        };
    }
    return undefined;
};

const program = new Command("stress")
    .option("-c, --config <value>", "Bridge config path")
    .option("-ap, --parallel-creates <number>", "Amount of parallel account create accounts")
    .option("-ai, --create-iterations <number>", "Amount of iterations to run for create accounts")
    .option("-cp, --parallel-claims <number>", "Amount of parallel claim accounts")
    .option("-ci, --claim-iterations <number>", "Amount of iterations to run for claim accounts")
    .action(async (args) => {
        const parsedArgs = parse(args);
        if (parsedArgs) {
            const stressRunner = new Stress(parsedArgs);
            await stressRunner.run();
            process.exit(0);
        } else {
            program.help();
            process.exit(1);
        }
    });
export default program;
